package tako.wisers.com.android.apis.parser;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public abstract class XMLParserBase {

	protected void build(String path) throws Exception {
		InputStream is = this.getClass().getResourceAsStream(path);
		build(is);
	}

	protected void build(InputStream is) throws FactoryConfigurationError,
			IOException, ParserConfigurationException, SAXException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder mBuilder = factory.newDocumentBuilder();
			Document document = mBuilder.parse(is);
			NodeList nodes = document.getChildNodes();
			parser(nodes);
		}  finally {
			if (is != null) {
				is.close();
			}
		}
	}
	
	protected void parser(NodeList nodes) {
		if (nodes == null)
			return;
		int len = nodes.getLength();
		for (int i = 0; i < len; i++) {
			Node node = nodes.item(i);
			this.tagNameSwitch(node);
		}
	}
	
	protected String getNodeAttribute(Node node, String key) {
		NamedNodeMap nodeParams = node.getAttributes();
		Node nodeAtrr = nodeParams.getNamedItem(key);
		if (nodeAtrr == null)
			return null;
		return nodeAtrr.getNodeValue();
	}
	
	protected abstract void tagNameSwitch(Node node);


}